package com.jy.appmarket.utils;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;

import com.jy.appmarket.model.UpdateItem;
import com.jy.appmarket.model.UpdateModel;

public final class AppUpdateUtils {

	public static final UpdateModel getUpdateModel(Context context) {
		if (context == null) {
			return null;
		}

		UpdateModel um = new UpdateModel();
		int[] wh = UITools.getDeviceScreenWidthHeight(context);
		um.setResolution(wh[0] + "x" + wh[1]);
		um.setModel(Build.MODEL);
		um.setSdkVersion(Build.VERSION.SDK_INT);
		List<UpdateItem> sysApps = new ArrayList<UpdateItem>();
		List<UpdateItem> userApps = new ArrayList<UpdateItem>();

		List<PackageInfo> packages = GetInstalledPackagesCompat.getInstalledPackages(context,
				PackageManager.GET_SIGNATURES);

		for (PackageInfo pi : packages) {
			UpdateItem ui = new UpdateItem();
			ui.setPackageName(pi.packageName);
			ui.setVersionCode(String.valueOf(pi.versionCode));
			ui.setVersionName(pi.versionName);
			String signature = DigestUtil.computeMd5forPkg(pi.signatures[0].toByteArray());
			ui.setCerStrMd5(signature);
			String path = pi.applicationInfo.sourceDir;
			ui.setFileMd5(CryptoUtil.getFileMD5(path));
			if ((pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
				// system app
				sysApps.add(ui);
			} else {
				// user app
				userApps.add(ui);
			}
		}
		um.setSysApps(sysApps);
		um.setUserApps(userApps);
		return um;
	}
}